import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Select, Space, Row, Col, Upload, message, Image } from 'antd';
import { PlusOutlined, MinusCircleOutlined, InboxOutlined } from '@ant-design/icons';

import { urlMap, uploadMap } from '@/utils';
import { getCityList } from '@/api/city';
import { uploadArticlePicture, deleteArticlePicture, publishArticle } from '@/api/cultruePop';

const ArticleComponents = (props) => {
    const { title } = props;
    const [form] = Form.useForm();
    const [fileList, setFileList] = React.useState({});
    const [cityData, setCityData] = useState([]);
    const [firstArticleToken, setFirstArticleToken] = useState(null);
    const [previewInfo, setPreviewInfo] = React.useState({
        visible: false,
        url: '',
    });

    const onFinish = (values) => {
        if (values?.content) {
            values?.content?.forEach((item) => {
                if (item.type === 'image') {
                    item.imagePath = item?.url?.file.name;
                    item.type = 'image';
                    item.imageType = 'content';
                    item.altText = item.imageName;
                    item.description = item.description;
                    delete item.url;
                    delete item.imageName;
                }
                if (item.type === 'list') {
                    item.listItems = item.items.join('；');
                    delete item.items;
                }
                if (item.type === 'video') {
                    item.videoPath = item?.url?.file.name;
                    item.type = 'video';
                    delete item.url;
                }
            });
        }

        const formData = {
            title: values?.title,
            content: values?.content,
            description: values?.description,
            articleToken: values?.cover?.file?.response?.data?.articleToken,
            cover: {
                imagePath: values?.cover?.file.name,
                imageType: 'cover',
                altText: values?.cover?.file.name.split('.')[0],
                description: values?.cover?.file.name.split('.')[0],
            },
            place: values.place,
            tags: values.tags,
        };
        publishArticle(formData).then((res) => {
            if (res.code === 200) {
                message.success('文章发布成功');
                setFirstArticleToken(null);
                form.resetFields();
            }
        });
    };

    // 上传处理逻辑
    //   const handleUpload = async (options) => {
    //     const { file, onSuccess, onError, field } = options;
    //     const formData = new FormData();
    //     formData.append('file', file);

    //     try {
    //         const res = await uploadArticlePicture(formData);

    //         // // 再检查业务状态码
    //         if (res.code !== 200) {
    //             throw new Error(res.message || '业务逻辑错误');
    //         }
    //         const rawValue = form.getFieldValue(field);
    //         const currentValue = Array.isArray(rawValue) ? rawValue : [].concat(rawValue || []);
    //         form.setFieldsValue({
    //           [field]: [
    //               ...currentValue.filter(Boolean),
    //               {
    //                   // 添加元数据
    //                   meta: {
    //                       uploadTime: new Date().toISOString(),
    //                       fileSize: file.size
    //                   },
    //                   // 原始字段
    //                   ...{
    //                       uid: file.uid,
    //                       name: file.name,
    //                       status: 'done',
    //                       url: res.data.url,
    //                       articleToken: res.data.articleToken
    //                   }
    //               }
    //           ]
    //       });

    //         onSuccess(res);
    //         message.success(`${file.name} 上传成功`);
    //     } catch (error) {
    //         message.error(`${file.name} 上传失败: ${error.message}`);
    //         onError(error);
    //     }
    // };
    const handleUpload = async (options) => {
        const { file, onSuccess, onError, field } = options;
        const formData = new FormData();
        formData.append('file', file);

        // 安全获取封面字段值并转换为数组
        const coverValue = form.getFieldValue('cover');
        const coverFiles = Array.isArray(coverValue) ? coverValue : [coverValue].filter(Boolean);

        // 安全获取内容字段值
        const contentValue = form.getFieldValue('content') || [];

        // 携带已有token发起请求
        if (firstArticleToken) {
            formData.append('articleToken', firstArticleToken);
        }

        try {
            const res = await uploadArticlePicture(formData);

            if (res.code !== 200) {
                throw new Error(res.message || '业务逻辑错误');
            }
            if (!firstArticleToken) {
                setFirstArticleToken(res.data.articleToken);
            }

            // 更新表单字段值
            const rawValue = form.getFieldValue(field);
            const currentValue = Array.isArray(rawValue) ? rawValue : [].concat(rawValue || []);
            form.setFieldsValue({
                [field]: [
                    ...currentValue.filter(Boolean),
                    {
                        meta: {
                            uploadTime: new Date().toISOString(),
                            fileSize: file.size,
                        },
                        ...{
                            uid: file.uid,
                            name: file.name,
                            status: 'done',
                            url: res.data.url,
                            articleToken: res.data.articleToken,
                        },
                    },
                ],
            });

            onSuccess(res);
            message.success(`${file.name} 上传成功`);
        } catch (error) {
            message.error(`${file.name} 上传失败: ${error.message}`);
            onError(error);
        }
    };

    // 预览图片处理逻辑
    const handlePreview = (file) => {
        setPreviewInfo({
            visible: true,
            url: file.url || URL.createObjectURL(file.originFileObj),
        });
    };

    // 删除处理逻辑
    const handleRemove = async (file, field) => {
        try {
            const finalToken = file?.articleToken || file?.response?.data?.articleToken;
            const fileName = file?.response?.data?.url.split('/').pop();
            // 调用后端删除接口（需要先创建对应的 API 方法）
            if (!finalToken) {
                throw new Error('缺少文件标识符');
            }
            await deleteArticlePicture({
                articleToken: finalToken,
                fileName: fileName,
            });

            // 更新表单数据
            const rawValue = form.getFieldValue(field);
            const currentValue = Array.isArray(rawValue) ? rawValue : [].concat(rawValue || []);
            const newValue = currentValue.filter((item) => item.uid !== file.uid);

            form.setFieldsValue({ [field]: newValue });

            message.success(`${file.name} 删除成功`);
            return true;
        } catch (error) {
            message.error(`${file.name} 删除失败: ${error.message}`);
            return false;
        }
    };

    // 封面图片上传组件
    const coverUploadProps = {
        customRequest: (options) => handleUpload({ ...options, field: 'cover' }),
        onRemove: (file) => handleRemove(file, 'cover'),
        onChange: ({ fileList }) => setFileList((prev) => ({ ...prev, cover: fileList })),
        listType: 'picture-card',
        showUploadList: { showPreviewIcon: true },
        onPreview: handlePreview,
        maxCount: 1,
        itemRender: (originNode, file) => (
            <div className={fileList.cover?.length ? 'ant-upload-list-item-disabled' : ''}>{originNode}</div>
        ),
    };

    // 内容区块的图片上传组件
    const createContentUploadProps = (name) => ({
        customRequest: (options) => handleUpload({ ...options, field: ['content', name, 'url'] }),
        onRemove: (file) => handleRemove(file, ['content', name, 'url']),
        onChange: ({ fileList }) => setFileList((prev) => ({ ...prev, [name]: fileList })),
        listType: 'picture',
        showUploadList: { showPreviewIcon: true },
        onPreview: handlePreview,
        maxCount: 1,
    });

    useEffect(() => {
        form.setFieldsValue({
            cover: [],
            content: [],
        });
    }, []);

    useEffect(() => {
        const fetchCities = async () => {
            try {
                const citiesData = await getCityList();
                const { data: cityList } = citiesData;
                const convertedCities = cityList.map((city) => ({
                    key: city.cityId,
                    value: city.cityName,
                }));

                const sortedCities = [...convertedCities].sort((a, b) => {
                    if (a.value === '广州') return -1;
                    if (b.value === '广州') return 1;
                    return 0;
                });
                setCityData(sortedCities);
            } catch (error) {
                setCityData([]);
            }
        };
        fetchCities();
    }, []);

    return (
        <>
            <Form form={form} onFinish={onFinish}>
                <div style={{ maxWidth: 800, margin: '0 auto' }}>
                    <h2
                        style={{
                            fontSize: 24,
                            fontWeight: 600,
                            textAlign: 'center',
                            marginBottom: 32,
                            color: '#1f1f1f',
                        }}
                    >
                        文章发布
                    </h2>
                    <Form.Item
                        label="文章标题"
                        name="title"
                        rules={[
                            {
                                required: true,
                                message: '请输入文章标题',
                            },
                        ]}
                    >
                        <Input placeholder="输入文章标题" />
                    </Form.Item>

                    <Form.Item label="文章描述" name="description" rules={[{ required: true }]}>
                        <Input.TextArea placeholder="输入文章描述" rows={3} />
                    </Form.Item>
                    <Form.Item label="文章类型" name="tags" rules={[{ required: true, message: '请选择类型' }]}>
                        <Select placeholder="请选择类型">
                            <Select.Option value="1">传统建筑</Select.Option>
                            <Select.Option value="2">特色美食</Select.Option>
                            <Select.Option value="3">地方习俗</Select.Option>
                            <Select.Option value="4">手工艺</Select.Option>
                            <Select.Option value="5">传统服饰</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="所在地区" name="place" rules={[{ required: true }]}>
                        <Select
                            loading={cityData.length === 0}
                            // onChange={setSelectedValue}
                        >
                            {cityData.map((item) => (
                                <Select.Option key={item.key} value={item.key}>
                                    {item.value}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item label="封面图片" name="cover" rules={[{ required: true }]}>
                        <Upload.Dragger {...coverUploadProps} listType="picture" maxCount={1} accept="image/*">
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined />
                            </p>
                            <p>点击或拖拽上传封面</p>
                        </Upload.Dragger>
                    </Form.Item>

                    <Form.List name="content">
                        {(fields, { add, remove }) => (
                            <div style={{ marginBottom: 24 }}>
                                {fields.map(({ key, name, ...restField }) => (
                                    <div
                                        key={key}
                                        style={{
                                            position: 'relative',
                                            marginBottom: 16,
                                            padding: 16,
                                            border: '1px solid #d9d9d9',
                                            borderRadius: 6,
                                        }}
                                    >
                                        <MinusCircleOutlined
                                            onClick={() => remove(name)}
                                            style={{
                                                position: 'absolute',
                                                right: 16,
                                                top: 16,
                                                color: '#ff4d4f',
                                                zIndex: 1,
                                            }}
                                        />
                                        <div
                                            style={{
                                                display: 'flex',
                                                flexWrap: 'wrap',
                                                gap: 24,
                                                position: 'relative',
                                                paddingTop: 32,
                                            }}
                                        >
                                            <div
                                                style={{
                                                    display: 'flex',
                                                    gap: 24,
                                                    alignItems: 'flex-start',
                                                    marginBottom: 16,
                                                    width: '100%',
                                                }}
                                            >
                                                {/* 组件类型选择 */}
                                                <Form.Item
                                                    {...restField}
                                                    name={[name, 'type']}
                                                    label="组件类型"
                                                    rules={[{ required: true }]}
                                                    style={{ flex: 1 }}
                                                >
                                                    <Select placeholder="选择类型">
                                                        <Select.Option value="heading">标题</Select.Option>
                                                        <Select.Option value="paragraph">段落</Select.Option>
                                                        <Select.Option value="image">图片</Select.Option>
                                                        <Select.Option value="list">列表</Select.Option>
                                                        <Select.Option value="video">视频</Select.Option>
                                                    </Select>
                                                </Form.Item>

                                                <Form.Item noStyle dependencies={[['content', name, 'type']]}>
                                                    {({ getFieldValue }) => {
                                                        const type = getFieldValue(['content', name, 'type']);
                                                        return (
                                                            type === 'heading' && (
                                                                <Form.Item
                                                                    {...restField}
                                                                    name={[name, 'level']}
                                                                    label="标题级别"
                                                                    rules={[{ required: true }]}
                                                                    style={{ flex: 1 }}
                                                                >
                                                                    <Select>
                                                                        <Select.Option value={1}>H1</Select.Option>
                                                                        <Select.Option value={2}>H2</Select.Option>
                                                                        <Select.Option value={3}>H3</Select.Option>
                                                                    </Select>
                                                                </Form.Item>
                                                            )
                                                        );
                                                    }}
                                                </Form.Item>
                                            </div>

                                            <Form.Item noStyle dependencies={[['content', name, 'type']]}>
                                                {({ getFieldValue }) => {
                                                    const type = getFieldValue(['content', name, 'type']);
                                                    return (
                                                        <div
                                                            style={{
                                                                display: 'flex',
                                                                flexDirection: 'column',
                                                                gap: 16,
                                                                width: '100%',
                                                            }}
                                                        >
                                                            {type === 'heading' && (
                                                                <Form.Item
                                                                    {...restField}
                                                                    name={[name, 'textContent']}
                                                                    label="标题内容"
                                                                    rules={[{ required: true }]}
                                                                >
                                                                    <Input placeholder="输入标题内容" />
                                                                </Form.Item>
                                                            )}

                                                            {type === 'paragraph' && (
                                                                <Form.Item
                                                                    {...restField}
                                                                    name={[name, 'textContent']}
                                                                    label="段落内容"
                                                                    rules={[{ required: true }]}
                                                                >
                                                                    <Input.TextArea rows={4} />
                                                                </Form.Item>
                                                            )}

                                                            {type === 'image' && (
                                                                <>
                                                                    <Form.Item
                                                                        {...restField}
                                                                        name={[name, 'url']}
                                                                        label="图片上传"
                                                                        rules={[{ required: true }]}
                                                                    >
                                                                        <Upload.Dragger
                                                                            {...createContentUploadProps(name)}
                                                                            name="image"
                                                                            action="/upload"
                                                                            maxCount={1}
                                                                            accept="image/*"
                                                                        >
                                                                            <p>点击或拖拽上传图片</p>
                                                                        </Upload.Dragger>
                                                                    </Form.Item>
                                                                    <Form.Item
                                                                        {...restField}
                                                                        name={[name, 'imageName']}
                                                                        label="图片名称"
                                                                        rules={[{ required: true }]}
                                                                    >
                                                                        <Input placeholder="输入图片名称" />
                                                                    </Form.Item>
                                                                    <Form.Item
                                                                        {...restField}
                                                                        name={[name, 'description']}
                                                                        label="图片描述"
                                                                        rules={[{ required: true }]}
                                                                    >
                                                                        <Input placeholder="输入图片描述" />
                                                                    </Form.Item>
                                                                </>
                                                            )}
                                                            {type === 'video' && (
                                                                <>
                                                                    <Form.Item
                                                                        {...restField}
                                                                        name={[name, 'url']}
                                                                        label="视频上传"
                                                                        rules={[{ required: true }]}
                                                                    >
                                                                        <Upload.Dragger
                                                                            {...createContentUploadProps(name)}
                                                                            accept="video/*"
                                                                            maxCount={1}
                                                                        >
                                                                            <p>点击或拖拽上传视频（MP4格式）</p>
                                                                        </Upload.Dragger>
                                                                    </Form.Item>
                                                                    <Form.Item
                                                                        {...restField}
                                                                        name={[name, 'description']}
                                                                        label="视频描述"
                                                                        rules={[{ required: true }]}
                                                                    >
                                                                        <Input placeholder="输入视频描述" />
                                                                    </Form.Item>
                                                                </>
                                                            )}
                                                            {type === 'list' && (
                                                                <>
                                                                    <Form.Item
                                                                        {...restField}
                                                                        name={[name, 'textContent']}
                                                                        label="列表名称"
                                                                        rules={[
                                                                            {
                                                                                required: true,
                                                                                message: '请输入列表名称',
                                                                            },
                                                                        ]}
                                                                    >
                                                                        <Input
                                                                            placeholder="例如：制作步骤"
                                                                            style={{ width: 400 }}
                                                                        />
                                                                    </Form.Item>

                                                                    <Form.List name={[name, 'items']}>
                                                                        {(subFields, subOpt) => (
                                                                            <div
                                                                                style={{
                                                                                    display: 'flex',
                                                                                    flexDirection: 'column',
                                                                                    gap: 8,
                                                                                }}
                                                                            >
                                                                                {subFields.map((subField, index) => (
                                                                                    <Space
                                                                                        key={subField.key}
                                                                                        align="baseline"
                                                                                    >
                                                                                        {/* 添加标签容器 */}
                                                                                        <div
                                                                                            style={{
                                                                                                width: 73,
                                                                                                textAlign: 'right',
                                                                                                visibility:
                                                                                                    index === 0
                                                                                                        ? 'visible'
                                                                                                        : 'hidden',
                                                                                                color: 'rgba(0, 0, 0, 0.88)',
                                                                                                fontSize: 14,
                                                                                                lineHeight: '22px',
                                                                                            }}
                                                                                        >
                                                                                            {index === 0 && (
                                                                                                <span>列表项：</span>
                                                                                            )}
                                                                                        </div>

                                                                                        <Form.Item
                                                                                            {...subField}
                                                                                            name={[subField.name]}
                                                                                            rules={[
                                                                                                {
                                                                                                    required: true,
                                                                                                    message:
                                                                                                        '请输入列表项内容',
                                                                                                },
                                                                                            ]}
                                                                                            style={{ marginBottom: 8 }}
                                                                                        >
                                                                                            <Input
                                                                                                placeholder="请输入列表项内容"
                                                                                                style={{ width: 400 }}
                                                                                            />
                                                                                        </Form.Item>
                                                                                        <MinusCircleOutlined
                                                                                            onClick={() =>
                                                                                                subOpt.remove(
                                                                                                    subField.name
                                                                                                )
                                                                                            }
                                                                                            style={{ color: '#ff4d4f' }}
                                                                                        />
                                                                                    </Space>
                                                                                ))}
                                                                                <Form.Item style={{ marginTop: 16 }}>
                                                                                    <Button
                                                                                        type="dashed"
                                                                                        onClick={() => subOpt.add()}
                                                                                        icon={<PlusOutlined />}
                                                                                        style={{ width: 200 }}
                                                                                    >
                                                                                        添加列表项
                                                                                    </Button>
                                                                                </Form.Item>
                                                                            </div>
                                                                        )}
                                                                    </Form.List>
                                                                </>
                                                            )}
                                                        </div>
                                                    );
                                                }}
                                            </Form.Item>
                                        </div>
                                    </div>
                                ))}

                                <Form.Item>
                                    <Button onClick={() => add({ type: 'heading' })} block icon={<PlusOutlined />}>
                                        添加内容组件
                                    </Button>
                                </Form.Item>
                            </div>
                        )}
                    </Form.List>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" block>
                            发布文章
                        </Button>
                    </Form.Item>
                </div>
            </Form>
            <Image
                width={0}
                style={{ display: 'none' }}
                src={previewInfo.url}
                preview={{
                    visible: previewInfo.visible,
                    onVisibleChange: (visible) => {
                        setPreviewInfo((prev) => ({ ...prev, visible }));
                    },
                }}
            />
        </>
    );
};

export default ArticleComponents;
